import 'package:flutter/cupertino.dart';
import 'package:flutter_van_android/utils/router_manager.dart';

/// 扩展 BuildContext 对象，增加辅助方法
extension Context on BuildContext {
  // 不带参数的跳转
  Future<T?> routeTo<T extends Object?>(Type router) {
    return RouterManager.routeTo(this, router);
  }

  // 通过这种方式，可以先获取页面对象的实例
  // 然后通过实例对象去调用 arguments 方法，最后调用 to 即可完成路由跳转
  RT routeOf<RT extends RouterBridge>() {
    assert(RT != RouterBridge<dynamic>,
        "You must specify the route type, for example: \"context.routeOf<Page>()\";");
    return RouterManager.of<RT>(this);
  }
  // 添加带参数的替换路由方法
  Future<T?> replaceWith<RT extends RouterBridge<T>, T, R extends Object?>(
    RT Function() routeBuilder, {
    T? arguments,
    R? result,
  }) {
    final route = routeBuilder();
    return RouterManager.replace(
      this,
      route.runtimeType,
      arguments: arguments,
      result: result,
    );
  }

  // 添加安全获取参数的方法
  T? safeArg<T>() {
    try {
      return ModalRoute.of(this)?.settings.arguments as T?;
    } catch (e) {
      return null;
    }
  }
}
